package com.tea.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tea.Model.DeliveryCompany;
import com.tea.Model.dto.DeliveryListDTO;
import com.tea.Model.vo.DeliveryCompanyVO;
import com.tea.mapper.DeliveryCompanyMapper;
import com.tea.utils.Result;
import com.tea.utils.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 运力公司服务类
 */
@Service
@Slf4j
public class DeliveryCompanyService extends ServiceImpl<DeliveryCompanyMapper, DeliveryCompany> {
    
    @Resource
    private DeliveryCompanyMapper deliveryCompanyMapper;
    
    @Resource
    private WxUtil wxUtil;
    
    /**
     * 同步微信运力公司列表到数据库
     * @return 同步结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> syncDeliveryCompanies() {
        try {
            log.info("开始同步微信运力公司列表");
            
            // 调用微信接口获取运力列表
            Result<?> rawResult = wxUtil.executeWithTokenRetry(() -> getDeliveryListFromWx());
            if (!rawResult.isSuccess()) {
                log.error("获取微信运力列表失败: {}", rawResult.getMessage());
                return Result.error("获取微信运力列表失败: " + rawResult.getMessage());
            }
            
            // 类型安全转换 - rawResult.getData()就是DeliveryListDTO对象
            DeliveryListDTO deliveryListDTO = (DeliveryListDTO) rawResult.getData();
            if (deliveryListDTO == null || deliveryListDTO.getDeliveryList() == null) {
                log.error("微信运力列表数据为空");
                return Result.error("微信运力列表数据为空");
            }
            
            List<DeliveryListDTO.DeliveryInfo> deliveryList = deliveryListDTO.getDeliveryList();
            log.info("获取到{}家运力公司", deliveryList.size());
            
            int insertCount = 0;
            int updateCount = 0;
            
            for (DeliveryListDTO.DeliveryInfo deliveryInfo : deliveryList) {
                if (StrUtil.isBlank(deliveryInfo.getDeliveryId()) || StrUtil.isBlank(deliveryInfo.getDeliveryName())) {
                    log.warn("跳过无效的运力公司数据: {}", deliveryInfo);
                    continue;
                }
                
                // 检查是否已存在
                QueryWrapper<DeliveryCompany> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("delivery_id", deliveryInfo.getDeliveryId());
                DeliveryCompany existingCompany = getOne(queryWrapper);
                
                if (existingCompany != null) {
                    // 更新现有记录
                    if (!deliveryInfo.getDeliveryName().equals(existingCompany.getDeliveryName())) {
                        existingCompany.setDeliveryName(deliveryInfo.getDeliveryName());
                        existingCompany.setUpdateTime(LocalDateTime.now());
                        updateById(existingCompany);
                        updateCount++;
                        log.debug("更新运力公司: {} -> {}", deliveryInfo.getDeliveryId(), deliveryInfo.getDeliveryName());
                    }
                } else {
                    // 插入新记录
                    DeliveryCompany newCompany = new DeliveryCompany();
                    newCompany.setDeliveryId(deliveryInfo.getDeliveryId());
                    newCompany.setDeliveryName(deliveryInfo.getDeliveryName());
                    newCompany.setStatus(1); // 默认启用
                    newCompany.setCreateTime(LocalDateTime.now());
                    newCompany.setUpdateTime(LocalDateTime.now());
                    save(newCompany);
                    insertCount++;
                    log.debug("新增运力公司: {} -> {}", deliveryInfo.getDeliveryId(), deliveryInfo.getDeliveryName());
                }
            }
            
            log.info("同步微信运力公司列表完成，新增: {}家，更新: {}家", insertCount, updateCount);
            return Result.success("同步成功，新增: " + insertCount + "家，更新: " + updateCount + "家");
            
        } catch (Exception e) {
            log.error("同步微信运力公司列表异常", e);
            return Result.error("同步异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据运力公司名称获取编码
     * @param deliveryName 运力公司名称
     * @return 运力公司编码
     */
    public String getDeliveryIdByName(String deliveryName) {
        if (StrUtil.isBlank(deliveryName)) {
            return null;
        }
        
        // 先精确匹配
        String deliveryId = deliveryCompanyMapper.getDeliveryIdByName(deliveryName);
        if (StrUtil.isNotBlank(deliveryId)) {
            return deliveryId;
        }
        
        // 再模糊匹配
        deliveryId = deliveryCompanyMapper.getDeliveryIdByNameLike(deliveryName);
        if (StrUtil.isNotBlank(deliveryId)) {
            log.debug("运力公司名称模糊匹配成功: {} -> {}", deliveryName, deliveryId);
            return deliveryId;
        }
        
        log.warn("未找到运力公司编码: {}", deliveryName);
        return null;
    }
    
    /**
     * 获取所有启用的运力公司列表
     * @return 运力公司列表
     */
    public Result<List<DeliveryCompanyVO>> getActiveDeliveryCompanies() {
        try {
            List<DeliveryCompany> companies = deliveryCompanyMapper.selectActiveDeliveryCompanies();
            
            List<DeliveryCompanyVO> voList = companies.stream().map(company -> {
                DeliveryCompanyVO vo = new DeliveryCompanyVO();
                BeanUtils.copyProperties(company, vo);
                
                // 格式化时间
                if (company.getCreateTime() != null) {
                    vo.setCreateTime(company.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                if (company.getUpdateTime() != null) {
                    vo.setUpdateTime(company.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                
                // 设置状态描述
                vo.setStatusDesc();
                
                return vo;
            }).collect(Collectors.toList());
            
            return Result.success(voList);
            
        } catch (Exception e) {
            log.error("获取运力公司列表异常", e);
            return Result.error("获取运力公司列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有启用的运力公司列表（供ExpressCompanyMapping使用）
     */
    public List<DeliveryCompanyVO> getEnabledDeliveryCompanies() {
        List<DeliveryCompany> companies = deliveryCompanyMapper.selectActiveDeliveryCompanies();
        return companies.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    /**
     * 获取所有运力公司列表（包括禁用的）
     */
    public List<DeliveryCompanyVO> getAllDeliveryCompanies() {
        List<DeliveryCompany> companies = this.list();
        return companies.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    /**
     * 启用/禁用运力公司
     * @param id 运力公司ID
     * @param status 状态 0-禁用 1-启用
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateStatus(Long id, Integer status) {
        try {
            if (id == null || status == null || (status != 0 && status != 1)) {
                return Result.error("参数错误");
            }
            
            DeliveryCompany company = getById(id);
            if (company == null) {
                return Result.error("运力公司不存在");
            }
            
            company.setStatus(status);
            company.setUpdateTime(LocalDateTime.now());
            updateById(company);
            
            String statusDesc = status == 1 ? "启用" : "禁用";
            log.info("{}运力公司: {} ({})", statusDesc, company.getDeliveryName(), company.getDeliveryId());
            
            return Result.success(statusDesc + "成功");
            
        } catch (Exception e) {
            log.error("更新运力公司状态异常", e);
            return Result.error("操作异常: " + e.getMessage());
        }
    }

    /**
     * 将DeliveryCompany转换为DeliveryCompanyVO
     */
    private DeliveryCompanyVO convertToVO(DeliveryCompany company) {
        DeliveryCompanyVO vo = new DeliveryCompanyVO();
        BeanUtils.copyProperties(company, vo);
        
        // 格式化时间
        if (company.getCreateTime() != null) {
            vo.setCreateTime(company.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (company.getUpdateTime() != null) {
            vo.setUpdateTime(company.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        // 设置状态描述
        vo.setStatusDesc();
        
        return vo;
    }

    /**
     * 直接从微信API获取运力公司列表
     * @return 运力公司列表
     */
    private Result<DeliveryListDTO> getDeliveryListFromWx() {
        // 获取access token
        String accessToken = wxUtil.getAccessToken();
        
        // 构建请求URL
        String url = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/get_delivery_list?access_token=" + accessToken;
        
        log.info("开始获取微信运力id列表");
        
        // 发送请求（该接口需要空的JSON请求体）
        HttpResponse response = HttpRequest.post(url)
                .contentType("application/json")
                .body("{}")
                .timeout(15000)
                .execute();
        
        if (!response.isOk()) {
            log.error("获取运力id列表请求失败，HTTP状态码: {}", response.getStatus());
            return Result.error("请求失败，HTTP状态码: " + response.getStatus());
        }
        
        String responseBody = response.body();
        log.info("获取运力id列表响应: {}", responseBody);
        
        // 解析响应
        JSONObject result = JSON.parseObject(responseBody);
        int errcode = result.getIntValue("errcode");
        
        if (errcode == 0) {
            // 成功
            DeliveryListDTO deliveryListDTO = JSON.parseObject(responseBody, DeliveryListDTO.class);
            log.info("获取运力id列表成功，共{}家运力公司", deliveryListDTO.getCount());
            return Result.success(deliveryListDTO);
        } else if (errcode == 40001) {
            // access_token失效，抛出异常触发重试
            String errmsg = result.getString("errmsg");
            log.warn("access_token失效，准备重试: errcode={}, errmsg={}", errcode, errmsg);
            throw new RuntimeException("ACCESS_TOKEN_INVALID: " + errmsg);
        } else {
            // 其他微信API错误
            String errmsg = result.getString("errmsg");
            log.error("获取运力id列表失败: errcode={}, errmsg={}", errcode, errmsg);
            return Result.error("获取运力id列表失败: " + errmsg);
        }
    }
}